package com.gowants.pems.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.mapper.LoopMapper;
import com.gowants.pems.model.Loop;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.JSONList;
import com.gowants.pems.util.JSONMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/loop/")
public class LoopController extends  BaseController{
    @Autowired
    private LoopMapper mapper;

    /**
     * 获取开关柜列表
     * @param page
     * @param limit
     * @param reqData
     * @param req
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜列表查看", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
                           @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
                           @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
                           HttpServletRequest req)
    {
        if (!isPower("/loop/getList.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        JSONMap resultMap = new JSONMap();
        Loop record = new Loop();
        if (!"".equals(reqData))
        {
            JSONList jsonCondition = getCondition(reqData);

            for (Object cond : jsonCondition) {
                this.buildCondition(cond, record);
            }
        }
        if(StringUtils.isNotBlank(getUser().getOwnerId())) {
            record.setOwner(getUser().getOwnerId());
        }
        // 设置分页查询信息
        PageHelper.startPage(page, limit);
        List<Loop> list = mapper.select(record);
        PageInfo<Loop> pageInfo = new PageInfo<Loop>(list);
        // 赋值方法
        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

        return doResponse(req, "", resultMap);
    }



    @RequestMapping(value = "/getOneLoop", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜一条记录检索", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getOneLoop(String request, HttpServletRequest req){
        Loop loop=new Loop();
        String code ="";
        if (!isPower("/loop/getOneLoop.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            loop = mapper.selectById(id);
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, loop);
    }



    @RequestMapping(value = "/saveLoop", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜保存", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap saveLoop(String request, HttpServletRequest req){
        if (!isPower("/loop/saveLoop.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000036";
        try
        {
            Loop record = getRequestBody(request, Loop.class);
            record.setId(UUID.randomUUID().toString());
            record.setCreateUid(getUserId());
            record.setCreateTime(DateUtil.getDate());
            int count1 = mapper.checkName(record.getName());
            if(count1 > 0)
            {
                return doResponse(req, "TSMS_0000492", null);
            }
            int exeNum = mapper.insert(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }

    @RequestMapping(value = "/editLoop", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜修改", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap editLoop(String request, HttpServletRequest req){
        if (!isPower("/loop/editLoop.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000053";
        try
        {
            Loop record = getRequestBody(request, Loop.class);
            int count1 = mapper.checkNameForUpdate(record.getName(),record.getId());
            if(count1 > 0)
            {
                return doResponse(req, "TSMS_0000492", null);
            }
            int exeNum = mapper.update(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }


    /**
     * <删除>
     * @param request
     * @param req
     * @return
     * @remake
     */
    @RequestMapping(value = "/deleteLoop", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜删除", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap deleteLoop(String request, HttpServletRequest req)
    {
        if (!isPower("/loop/deleteLoop.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000048";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            int exeNum = mapper.delete(id);
            if(exeNum > 0)
            {
                code = "TSMS_0000050";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        return doResponse(req, code, null);
    }

    private void buildCondition(Object cond, Loop record)
    {
        JSONMap condition = JSONMap.parseJSONMap(cond.toString());

        String field = condition.getString("field");
        String keyword = condition.getString("keyword");

        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword))
        {
            switch (field)
            {
                case "id":
                    record.setId(keyword);
                    break;
                case "name":
                    record.setName(keyword);
                    break;
                case "station":
                    record.setStation(keyword);
                    break;
                case "ct":
                    record.setCt(Integer.parseInt(keyword));
                    break;
                case "type":
                    record.setType(Integer.parseInt(keyword));
                    break;
                case "telemetering":
                    record.setTelemetering(Integer.parseInt(keyword));
                    break;
                case "telesignalling":
                    record.setTelesignalling(Integer.parseInt(keyword));
                    break;
                case "supplyCircuit":
                    record.setSupplyCircuit(Integer.parseInt(keyword));
                    break;
                case "switchCabinet":
                    record.setSwitchCabinet(keyword);
                    break;
                case "itemType":
                    record.setItemType(Integer.parseInt(keyword));
                    break;
                case "detailedInformation":
                    record.setDetailedInformation(Integer.parseInt(keyword));
                    break;
                case "voltageLevel":
                    record.setVoltageLevel(Integer.parseInt(keyword));
                    break;

            }
        }
    }
}
